﻿/*
 * @Autor: PK
 * @Date: 2021/12/06 17:05:SS
 */

using System;
using System.Collections.Generic;
using System.Data;
using ShkSimulation.core.dao.input.resource;
using ShkSimulation.core.dao.statistic;
using ShkSimulation.core.dao.statistic.feature;
using ShkSimulation.core.optimization.extractor;

namespace ShkSimulation.core.dao.output.result {
	
	public abstract class DataTableResourceResult : AbstractDataTableResource, Result {

		protected Result result;
		protected ResultData resultData;
		
		public DataTableResourceResult(Result result) {
			this.uniqueKey = result.Uniquekey + ":DataTable";
			this.dataTable = new DataTable();
			this.result = result;
			this.resultData = result.TakeOutputData();
			this.dataTable.Columns.AddRange(GetColumns());
			SortedDictionary<string, CollectionReportData> sortedDictionary =
				new SortedDictionary<string, CollectionReportData>(resultData.Data, StringComparer.CurrentCultureIgnoreCase);
			
			foreach (var (collectionUniqueKey, collectionReportData) in sortedDictionary) {
				AppendData(collectionUniqueKey, collectionReportData);
			}
			DataTable newTable = dataTable.Clone();
			SortedList<string, DataRow> rows = new SortedList<string, DataRow>();
			foreach (var (key, dataRow) in rows) {
				newTable.Rows.Add(dataRow);
			}
		}

		protected abstract DataColumn[] GetColumns();

		public ResultData TakeOutputData() {
			return resultData;
		}

		public void AppendData(string collectionKey, CollectionReportData data) {
			SortedDictionary<VariableAndHourStatisticKey, StatisticInfo> sortedDictionary = 
				new SortedDictionary<VariableAndHourStatisticKey, StatisticInfo>(Comparer<VariableAndHourStatisticKey>.Create(
					(a, b) => {
						return a.ToString().CompareTo(b.ToString());
					}));
			foreach (var (variableAndHourStatisticKey, statisticInfo) in data) {
				sortedDictionary.Add(variableAndHourStatisticKey, statisticInfo);
			}
			foreach (var (variableAndHourStatisticKey, statisticInfo) in sortedDictionary) {
				AppendRows(collectionKey, variableAndHourStatisticKey, statisticInfo);
			}

		}

		protected abstract void AppendRows(string collectionKey, VariableAndHourStatisticKey variableAndHourStatisticKey, StatisticInfo statisticInfo);
		
		public abstract CellPoint GetValuePosition(int rowIndex);

		public CollectionReportData GetData(string collectionKey) {
			return resultData[collectionKey];
		}

		public bool ContainsData(string collectionKey) {
			return resultData.ContainsKey(collectionKey);
		}


	}
}